-- UIMercenaryCamp
-- Created by cheny3
-- 佣兵营地主界面

require "game/ui/form/shop/UIScrapShop"
require "game/ui/form/shop/UIPetShop"
require "game/ui/form/shop/UITankUse"
require "game/ui/form/shop/UIPetRecruitMain"
require "game/ui/form/shop/UIPetCampCard"
require "game/ui/form/shop/UICampCardBonus"

UIMercenaryCamp = class("UIMercenaryCamp", function()
    return cc.Layer:create();
end);

function UIMercenaryCamp.create()
    return UIMercenaryCamp.new();
end

-- 内部函数声明
local resize;

-- 构造函数
function UIMercenaryCamp:ctor()
    self:setName("UIMercenaryCamp");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/shop/MercenaryCamp.csb");
    self:addChild(node);
    self.node = node;

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册各种点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 检查通知
    self:checkNotify();

    -- BT飞入初始化
    self:setInit();

    -- 播放特效
    self:playMapEffect();

    -- 适配
    resize(node);
end

-- 检查通知
function UIMercenaryCamp:checkNotify()
    -- 兑换碎片气泡
    local leaderBubble = findChildByName(self.node, "bg/leader/bubble");
    leaderBubble:setLocalZOrder(1);
    local classId = PetShopM.getCanChangeScarp();
    if classId > 0 then
        -- 有需要显示的
        local bg = findChildByName(leaderBubble, "bg");
        local icon = findChildByName(leaderBubble, "icon");
        icon:loadTexture(getItemIconPath(ItemM.query(classId, "icon")));
        icon:setScale(0.7);
        -- 气泡轻微收缩
        leaderBubble:stopAllActions();
        playBubbleAnima(leaderBubble, false, 0.88, nil, nil, nil, 0.8);
    else
        leaderBubble:setVisible(false);
    end

    -- 检查按钮
    local goldHint = findChildByName(self.node, "BT/gold_tank_btn/hint");
    local normalHint = findChildByName(self.node, "BT/normal_tank_btn/hint");

    local goldTankClassId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", "gem");
    local normalTankClassId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", "money");
    local goldNum = ItemM.getAmount(ME.user, goldTankClassId);
    local normalNum = ItemM.getAmount(ME.user, normalTankClassId);

    checkBlueBubbleStatus(goldHint, goldNum);
    checkBlueBubbleStatus(normalHint, normalNum);

    -- 传送门气泡检查
    local gateBubble = findChildByName(self.node, "bg/gate/bubble");
    local petId = PetShopM.getCanHireSlime();
    if petId > 0 then
        -- 有需要显示的
        local bg = findChildByName(gateBubble, "bg");
        local icon = findChildByName(gateBubble, "icon");
        local scrapId = PetM.query(petId, "chips");
        -- 气泡轻微收缩
        gateBubble:setVisible(true);
        gateBubble:stopAllActions();
        playBubbleAnima(gateBubble, false, 0.70);
    else
        gateBubble:setVisible(false);
    end

    -- 月卡泡泡
    local cardBubble = findChildByName(self.node, "bg/camp_card/bubble");
    cardBubble:setVisible(false);
    cardBubble:stopAllActions();
    cardBubble.isPlaying = false;

    local cardIcon = findChildByName(cardBubble, "icon");

    local iconPath;
    if MonthCardM.cantakeBonus("pet_camp") then
        cardBubble:setVisible(true);
        iconPath = getItemIconPath(1512);
        cardIcon:loadTexture(iconPath);

        if not cardBubble.isPlaying then
            cardBubble:stopAllActions();
            playBubbleAnima(cardBubble, false, 0.70);
            cardBubble.isPlaying = true;
        end
    elseif MonthCardM.isCardFuncActived("pet_camp") and MonthCardM.isOverdue("pet_camp") then
        cardBubble:setVisible(true);
        iconPath = getWorkshopIconPath("guide/exclamation_mark");
        cardIcon:loadTexture(iconPath);

        if not cardBubble.isPlaying then
            cardBubble:stopAllActions();
            playBubbleAnima(cardBubble, false, 0.70);
            cardBubble.isPlaying = true;
        end
    end
end

-- 注册点击事件
function UIMercenaryCamp:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIMercenaryCamp");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 点击传送门
    local gateNode = findChildByName(node, "bg/gate");
    local gatePanel = findChildByName(gateNode, "click_panel");
    local bubbleImg = findChildByName(gateNode, "bubble/bg");
    local function onGateClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local uiPetRecruit = UIPetRecruitMain.create();
            UIMgr.getCurrentScene():addForm(uiPetRecruit);
            AudioM.playFx("cosmmic_gate");
        end
    end
    AddTouchEventListener(gatePanel, onGateClick);
    AddTouchEventListener(bubbleImg, onGateClick);

    -- 冈布奥的罐按钮
    local btnNormal = findChildByName(node, "BT/normal_tank_btn");
    local function onNormalClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            UIMgr.getCurrentScene():removeFormByName("UITankUse");
            local uiForm = UITankUse.create("money");
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end
    AddTouchEventListener(btnNormal, onNormalClick);

    local kerning = -3;
    if not isFullWidthLang() then
        kerning = -1;
    end
    TextStyleM.setTextStyle(btnNormal, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() + kerning);
    btnNormal:setTitleText(getLocStr("btn_text_normal_tank"));

    -- 黄金的罐按钮
    local btnGold = findChildByName(node, "BT/gold_tank_btn");
    local function onGoldClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            UIMgr.getCurrentScene():removeFormByName("UITankUse");
            local uiForm = UITankUse.create("camp");
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end
    AddTouchEventListener(btnGold, onGoldClick);
    TextStyleM.setTextStyle(btnGold, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnGold:setTitleText(getLocStr("btn_text_gold_tank"));

    -- 注册月卡点击事件
    local campCardNode = findChildByName(self.node, "bg/camp_card");
    local cabriteImg = findChildByName(campCardNode, "cabrite");
    local cardBubbleBg = findChildByName(campCardNode, "bubble/bg");

    local function onCardClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            if not MonthCardM.isOverdue("pet_camp") then
                UIMgr.getCurrentScene():removeFormByName("UICampCardBonus");
                local uiForm = UICampCardBonus.create("pet_camp");
                UIMgr.getCurrentScene():addForm(uiForm);
            elseif MonthCardM.isCardFuncActived("pet_camp") then
                UIMgr.getCurrentScene():removeFormByName("UIPetCampCard");
                local uiForm = UIPetCampCard.create();
                UIMgr.getCurrentScene():addForm(uiForm);
            end
        end
    end

    cabriteImg:addTouchEventListener(onCardClick);
    cardBubbleBg:addTouchEventListener(onCardClick)
end

-- 注册事件处理回调函数
function UIMercenaryCamp:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIMercenaryCamp", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIMercenaryCamp" then
            self:showBottomMenu(true);
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);

            if self.needRedraw then
                -- 刷新提示
                self:checkNotify();
                self.needRedraw = false;
            end

            if para["lose"] ~= "UITalentMain" and para["lose"] ~= "UICommunicating" then
                if not self.flying then
                    self:btFlyUp();
                end
            end
        elseif para["lose"] == "UIMercenaryCamp" then
            self:showBottomMenu(false);
        end
    end);

    -- 活动开始事件
    EventMgr.register("UIMercenaryCamp", event.ACTIVITY_CHANGE, function(args)
        local id = args["id"];
        if ActivityM.query(id, "rule") ~= "dungeon" then
            -- 不是地面迷宫
            return;
        end

        -- 刷新提示
        self:checkNotify();
        self.needRedraw = false;
    end);

    -- 活动结束事件
    EventMgr.register("UIMercenaryCamp", event.ACTIVITY_CLOSE, function(args)
        local id = args["id"];
        if ActivityM.query(id, "rule") ~= "dungeon" then
            -- 不是地面迷宫
            return;
        end

        -- 刷新提示
        self:checkNotify();
        self.needRedraw = false;
    end);

    -- 购买罐子事件
    EventMgr.register("UIMercenaryCamp", event.BUY_PUZZLE_BOX, function(para)
        -- 需要检查
        self.needRedraw = true;
    end);

    -- 使用罐子事件
    EventMgr.register("UIMercenaryCamp", event.USE_PUZZLE_BOX, function(para)
        -- 需要检查
        self.needRedraw = true;
    end);

    -- 关注兑换的事件
    EventMgr.register("UIMercenaryCamp", event.PET_SHOP_EXCHANGE, function(args)
        local goodsId = args.goodsId;
        if not goodsId then
            -- 自动更新，直接刷新
            self:checkNotify();
            self.needRedraw = false;
        else
            -- 设置需要检查
            self.needRedraw = true;
        end
    end);

    -- 关注激活月卡事件
    EventMgr.register("UIMercenaryCamp", event.BUY_GOODS, function(args)
        if MarketM.query(args.goodsId, "classify") == "pet_camp" then
            -- 自动更新，直接刷新
            self:checkNotify();
            self.needRedraw = false;

            local bonusList = args.bonus;

            if type(args.bonus[1]) == "number" then
                bonusList = {args.bonus};
            end
            showBonusNotifyForm(MarketM.query(args.goodsId, "name"), bonusList);
        end
    end);

       -- 领取佣兵营地月卡奖励
    EventMgr.register("UIMercenaryCamp", event.TAKE_CAMP_CARD_RET, function(args)
        self.needRedraw = true;
    end)

    -- 关注激活宠物
    EventMgr.register("UIMercenaryCamp", event.GAIN_PET, function()
        -- 检查
        self.needRedraw = true;
    end);

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIMercenaryCamp 界面析构清理");
            EventMgr.removeAll("UIMercenaryCamp");
            if UIMgr.getCurrentScene().mainMap then
                UIMgr.getCurrentScene().mainMap:show();
            end

            UIMgr.tryClearUnusedTextures();
        elseif ev == "enter" then
            UIMgr.getCurrentScene().mainMap:hide();
            -- TODO播放界面音效

            -- 依次检查是否有提醒
            self:checkReminder();
        end
    end);
end

-- 隐藏底部菜单
function UIMercenaryCamp:showBottomMenu(visible)
    local BT = findChildByName(self.node, "BT");
    BT:setVisible(visible);
end

-- 重绘
function UIMercenaryCamp:redraw()
    local leaderNode = findChildByName(self.node, "bg/leader");
    local slimeImg  = findChildByName(leaderNode, "slime");
    local bubbleBg  = findChildByName(leaderNode, "bubble/bg");
    local bg        = findChildByName(self.node, "bg");

    -- 底图
    bg:loadTexture(getMercenaryCampIconPath("bg1"));
    -- 佣兵首领
    slimeImg:loadTexture(getHeroIconPath(79));
    -- 播放呼吸动画
    playSlightAnima(slimeImg);

    -- 兑换/购买界面
    local function onClickLeader(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            UIMgr.getCurrentScene():removeFormByName("UIScrapShop");
            local uiForm = UIScrapShop.create();
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("market_open");
        end
    end
    slimeImg:addTouchEventListener(onClickLeader);
    bubbleBg:addTouchEventListener(onClickLeader);

    -- 检查当前佣兵营地月卡功能是否开启
    local isActiveCampCard = MonthCardM.isCardFuncActived("pet_camp");
    local campCardNode = findChildByName(self.node, "bg/camp_card");
    local cabriteImg = findChildByName(campCardNode, "cabrite");
    if isActiveCampCard then
        -- 播放呼吸动画
        playSlightAnima(cabriteImg, 0.8);
        campCardNode:setVisible(true);
    else
        campCardNode:setVisible(false);
    end
end

-- 注册点击阵营图片
function UIMercenaryCamp:registerClickCampImg(node, campId)
    local function onClickImg(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 打开雇佣界面
            UIMgr.getCurrentScene():removeFormByName("UIPetShop");
            local uiForm = UIPetShop.create(campId);
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("market_open");
        end
    end
    node:addTouchEventListener(onClickImg);
end

function UIMercenaryCamp:playMapEffect()
    local effectsNode = findChildByName(self.node, "CT/effect_node");

    -- 传送门光效
    local function playPortalAnimation()
        local function portalAnimation()
            local mercenaryPortalNode = findChildByName(effectsNode, "mercenary_portal");
            playEffect(mercenaryPortalNode, 1312);

            performWithDelay(self, portalAnimation, 4.3);
        end

        portalAnimation();
    end

    -- 风吹动画
    local function playTreeAnimation()
        local function playLeftTreeAnimation()
            -- 左边树光效
            local mercenaryTreeLeftNode = findChildByName(effectsNode, "mercenary_tree_left");
            playEffect(mercenaryTreeLeftNode, 1314, 12, 32);
        end

        local function playRightTreeAnimation()
            -- 右边树光效
            local mercenaryTreeRightNode = findChildByName(effectsNode, "mercenary_tree_right");
            playEffect(mercenaryTreeRightNode, 1315, -1, 46);
        end

        local function treeAnimation()
            playLeftTreeAnimation();
            playRightTreeAnimation();

            performWithDelay(self, treeAnimation, 1.9);
        end

        treeAnimation();
    end

    -- 风吹树动效果
    local function playSandAnimation()
        local function playSandAnimation1()
            -- 风沙光效1
            local mercenarySandNode = findChildByName(effectsNode, "mercenary_sand1");
            playEffect(mercenarySandNode, 1313, 0, 17);
        end

        local function playSandAnimation2()
            -- 风沙光效2
            local mercenarySandNode = findChildByName(effectsNode, "mercenary_sand2");
            playEffect(mercenarySandNode, 1313, 0, 10);
        end

        local function sandAnimation()
            playSandAnimation1();
            performWithDelay(self, playSandAnimation2, 1.5);

            performWithDelay(self, sandAnimation, 5);
        end

        sandAnimation();
    end

    playPortalAnimation();
    playSandAnimation();
    playTreeAnimation();
end

-- 关于下部飞入效果的初始化
function UIMercenaryCamp:setInit()
    self.flying = false;

    local BT = findChildByName(self.node, "BT");
    self.btInitPosition = BT:getPositionY();
end

-- 获得焦点隐藏焦点
function UIMercenaryCamp:btFlyUp()
    local bottom = findChildByName(self.node, "BT");

    -- 动作保护
    bottom:stopAllActions();
    bottom:setVisible(false);
    bottom:setPosition(bottom:getPositionX(), self.btInitPosition);

    self.flying = true;

    local function callback()
        self.flying = false;
    end

    if bottom then
        bottom:setVisible(true);

        FormEffectM.btPopUpFromBottom(self, callback);
    end
end

-- 适配
function resize(node)
    -- bg置于底部并缩放至合适大小
    AlignM.alignToCenter(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 依次检查是否有提醒
function UIMercenaryCamp:checkReminder()
    local checkList = {"pet_camp"};
    local bt = findChildByName(self.node, "BT");
    bt:setVisible(true);
    local function callback(desc)
        local function okFunc()
            -- 继续检查是否还有其他提醒
            self:checkReminder();
        end
        self:hideBT();
        confirm2(CONFIRM_TYPE_OK, getLocStr("slime_note"), desc, okFunc);
    end

    -- 检查进度
    if not self.checkProgress then
        self.checkProgress = 1;
    end

    print("self.checkProgress:"..self.checkProgress);
    for i = self.checkProgress, #checkList do
        local ret = FeatureItemM.checkReminder(checkList[i], callback);
        if ret == true then
            -- 每次检查一个提醒，确认后再继续
            self.checkProgress = i + 1;
            return;
        end
    end
end

-- 失去焦点,隐藏Bottom
function UIMercenaryCamp:hideBT()
    local bottom = findChildByName(self.node, "BT");
    if bottom then
        bottom:setVisible(false);
    end
end